﻿using System.ComponentModel;
using K9Nano.AspNetCore.Filters;
using K9Nano.Extensions;
using K9Nano.FileStorage;
using K9Nano.Resources;
using K9Nano.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace K9Nano.AspNetCore.Controllers;

[Route("api/file")]
[Description("文件管理接口")]
[RequestLogging(Enabled = false)]
public class FileController(IFileStorage storage, IOptions<K9Options> optionAccessor) : ApiControllerBase
{
    /// <summary>
    /// 上传附件
    /// </summary>
    /// <param name="file"></param>
    /// <returns>访问地址</returns>
    [HttpPost("upload")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public async Task<string> Upload([FromForm] IFormFile file)
    {
        using var inputStream = file.OpenReadStream();
        var ext = Path.GetExtension(file.FileName) ?? string.Empty;
        var result = await storage.SaveAsync(inputStream, ext, true, HttpContext.RequestAborted);

        var uri = Environment.OSVersion.Platform == PlatformID.Win32NT
            ? result.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
            : result;

        return optionAccessor.Value.StorageRequestPath + uri;
    }

    /// <summary>
    /// 获取文件资源
    /// </summary>
    /// <param name="id">资源ID</param>
    [ApiExplorerSettings(IgnoreApi = true)]
    [HttpGet("{id}")]
    [AllowAnonymous]
    public IActionResult GetResource(string id, [FromServices] IResourceManager manager)
    {
        var fileRes = manager.Get<FileResource>(id);
        if (fileRes == null)
        {
            return Content("您访问的资源已经失效或者您没有访问权限，资源ID: " + id, "text/plain", System.Text.Encoding.UTF8);
        }
        if (!System.IO.File.Exists(fileRes.FilePath))
        {
            return Content("您访问的资源已经失效，资源ID: " + id, "text/plain", System.Text.Encoding.UTF8);
        }

        var stream = System.IO.File.OpenRead(fileRes.FilePath);
        var contentType = MimeUtils.GetContentType(Path.GetExtension(fileRes.FileName));
        return File(stream, contentType, fileRes.FileName);

    }
}

